<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\model\AdminConfig;
use addons\qingdongams\model\Customer as CustomerModel;
use addons\qingdongams\model\CustomerEnterprise;
use addons\qingdongams\model\CustomerEnterpriseDetail;
use fast\Http;
use think\Db;
use think\Exception;
use think\Log;

/**
 * 公司信息公共接口
 */
class Enterprise extends StaffApi {
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = '*';
    /**
     * @var \addons\qingdongams\model\CustomerEnterprise;
     */
    protected $enterpriseModel = null;
    /**
     * @var \addons\qingdongams\model\CustomerEnterpriseDetail;
     */
    protected $detailModel = null;
    protected $customerModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->enterpriseModel = new CustomerEnterprise();
        $this->detailModel = new CustomerEnterpriseDetail();
        $this->customerModel = new \addons\qingdongams\model\Customer();
        $this->enterpriseCode = AdminConfig::where(array('type'=>'juhe','field'=>'juhe_api'))->value('value');
        $this->detailCode = AdminConfig::where(array('type'=>'juhe','field'=>'juhe_secret'))->value('value');
    }

    /**
     * 根据关键字获取 列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getEnterprise(){
        $keywords = input('keywords');
        if(!$keywords){
            $this->error('请输入要查询的企业名称');
        }
        $where['keywords'] = ['like','%'.$keywords.'%'];
        $list = $this->enterpriseModel->where($where)->select();
        if(count($list)==0) {
            $list = $this->curl_enterprise($keywords);
            if(!is_array($list) || !$list){
                $this->error($list);
            }
            $this->success('',$list);
        }else{
            $data = [];
            $list = collection($list)->toArray();
            foreach($list as $k=>$v){
                $data = array_merge($data,json_decode($v['content'],true));
            }
            $this->success('',$data);
        }
    }

    /**
     * 根据公司名字查询
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDetail(){
        $name = input('name');
        if(!$name){
            $this->error('请输入要查询的公司名字');
        }
        $res = $this->detailModel->where(['name'=>$name])->find();
        if(!$res) {
            $res = $this->curl_enterprise_detail($name);
            if(!$res){
                $this->error('未查询到此公司');
            }
        }else{
            $res = json_decode($res['content'],true);
        }
        if(!$res){
            $this->error('暂无此公司信息！');
        }
        // 工商信息
        $enterprise = [
            'basic' => $res,// 基本信息
            'employees_total' => count($res['employees']),
            'employees' => $res['employees'],// 高管
            'partners_total' => count($res['partners']),
            'partners' => $res['partners'],// 股东
            'branches_total' => count($res['branches']),
            'branches' => $res['branches'],// 分支结构
            'oupay_total' => 0,
            'oupay' => [],// 对外投资
            'changerecords_total' => count($res['changerecords']),
            'changerecords' => $res['changerecords'],// 变更信息
        ];
        // 风险信息
        $risk = [
            'abnormal_total'  =>  isset($res['abnormal_items']) ? count($res['abnormal_items']) : 0,
            'abnormal'  =>  isset($res['abnormal_items']) ? $res['abnormal_items'] : [],// 经营异常
        ];
        $data = [
            'name'      =>  $res['name'],// 公司名字
            'econ_kind' =>  $res['econ_kind'],// 注册资本
            'oper_name' =>  $res['oper_name'],// 法人代表
            'start_date'=>  $res['start_date'],// 成立日期
            'address'   =>  $res['address'],// 地址
            'money'     =>  $res['regist_capi_new'],// 注册资本金额
            'scope'     =>  $res['scope'],// 经营范围
            'belong_org'=>  $res['belong_org'],// 发政机关（所属局）
            'status'    =>  $res['status'],// 经营情况？
            'province'  =>  $res['province'],// 省份缩写
            'enterprise'=>$enterprise,// 工商信息
            'risk'  =>  $risk // 风险
        ];
        $this->success('',$data);
    }
    /**
     * 获取企业信息
     * @param $customerId
     * @throws \think\exception\DbException
     */
	public function curl_enterprise($keywords){
	    $name = urlencode($keywords);
        if(empty($this->enterpriseCode)){
            $this->error('后台未设置聚合appid，请联系管理员');
        }
        $url = "http://japi.juhe.cn/enterprise/simpleList?key=".$this->enterpriseCode."&keyword=".$name;
        $res = Http::get($url);
        Log::write('查询信息返回-'.$keywords.'---'.$url.'====='.$res);
        $res = json_decode($res,true);

        if(empty($res) || $res['error_code'] != 0){
            $this->error($res['reason']);
        }
        $save = [
            'keywords'   =>  $keywords,
            'total'         =>  $res['result']['data']['total'],
            'num'           =>  $res['result']['data']['num'],
            'content'       =>  is_array($res['result']['data']['items']) ? json_encode($res['result']['data']['items']) : $res['result']['data']['items'],
            'author_id'     =>  $this->auth->id,
            'author_'       =>  $this->auth->name,
            'res_status'    =>  0,
        ];
        try {
            Db::startTrans();
            $this->enterpriseModel->allowField(true)->save($save);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        return $res['result']['data']['items'];
    }

    /**
     * 获取精准查询结果
     * @param $customerId
     * @throws \think\exception\DbException
     */
    public function curl_enterprise_detail($keywords){
        $name = urlencode($keywords);
        $url = "http://japi.juhe.cn/enterprise/getDetailByName?key=".$this->detailCode."&keyword=".$name;
        $res = Http::get($url);
        Log::write('查询精准信息返回-'.$keywords.'---'.$url.'===='.$res);
        $res = json_decode($res,true);
        if($res['error_code'] != 0){
            $this->error($res['reason']);
        }
        $save = [
            'name'   =>  $keywords,
            'content'       =>  is_array($res['result']['data']) ? json_encode($res['result']['data'],JSON_UNESCAPED_UNICODE) : $res['result']['data'],
            'author_id'     =>  $this->auth->id,
            'author_'       =>  $this->auth->name,
            'res_status'    =>  0,
        ];
        try {
            Db::startTrans();
            $this->detailModel->allowField(true)->save($save);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        return $res['result']['data'];
    }

    // 获取 上级id
    public static function getPid($id,$arr){
        $detail = CustomerModel::get($id);
        array_push($arr,$detail['parent_id']);
        if($detail['parent_id'] != 0){
            return ['id'=>$detail['parent_id'],'arr'=>$arr];
        }
        return self::getPid($detail['parent_id'],$arr);
    }

}
